package com.zlwy.activity;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.zlwy.adapter.MyFragmentPagerAdapter;
import com.zlwy.application.GlobalApplication;
import com.zlwy.debug.Logger;
import com.zlwy.dialog.ExitDialog;
import com.zlwy.entity.C_Result;
import com.zlwy.entity.User;
import com.zlwy.http.BagRequest;
import com.zlwy.http.LoginRequest;
import com.zlwy.http.VersionRequest;
import com.zlwy.http.WebSocketClient;
import com.zlwy.server.DownloadService;
import com.zlwy.server.DownloadService.DownloadBinder;
import com.zlwy.util.Util;
import com.zlwy.view.MyViewPager;


public class MainActivity extends FragmentActivity{
	
	private List<Fragment> fragments = new ArrayList<Fragment>();
	private MyViewPager pager;
	private MyFragmentPagerAdapter pagerAdapter;
	private View selfView;
	private View homeView;
	private View assetsView;
	private LayoutInflater inflater;
	private boolean isLogin = false;
	private User user;
	private HomeFragment hFragment;
	private CandleFragment cFragment;
	private String curVersion;
	private String serVersion;
	private String newVersionDownLoadUrl;
	private boolean isBinded;
	private DownloadBinder binder;	
	private TextView tvLgOrRt;
	
	/**
	 * 登录广播
	 */
	private BroadcastReceiver loginReceiver = new BroadcastReceiver(){
		public void onReceive(Context context, Intent intent) {
			user = (User) intent.getSerializableExtra("USER");	
			if(user!=null){
				isLogin = true;
				hFragment.setUser(user);
			}
			Logger.i("", "登陆完成！");
			initHomeTitle();
		}		
	};
	
	/**
	 * 退出广播
	 */
	private BroadcastReceiver exitReceiver = new BroadcastReceiver(){
		public void onReceive(Context context, Intent intent) {
			//退出
			user = null;
			isLogin = false;
			initHomeTitle();
			hFragment.setUser(null);
		}		
	};
	
	/**
	 * 修改登录密码广播
	 */
	private BroadcastReceiver chgLgPwdReceiver = new BroadcastReceiver(){

		public void onReceive(Context context, Intent intent) {
			user = null;
			isLogin = false;
			initHomeTitle();
			hFragment.setUser(null);
		}		
	};
	
	/**
	 * 设置支付密码成功广播
	 */
	private BroadcastReceiver setTPwdOkReceiver = new BroadcastReceiver(){
		public void onReceive(Context context, Intent intent) {
			MainActivity.this.user.setTradepwd(intent.getStringExtra("TPWD"));
		}		
	};
	
	/**
	 * 买入广播
	 */
	private BroadcastReceiver buyReceiver = new BroadcastReceiver(){
		public void onReceive(Context context, Intent intent) {
			user.setMjNum(intent.getStringExtra("DZMJ"));
		}		
	};
	
	/**
	 * 卖出广播
	 */
	private BroadcastReceiver saleReceiver = new BroadcastReceiver(){
		public void onReceive(Context context, Intent intent) {
			user.setYbNum(intent.getStringExtra("YB"));
			user.settYb(intent.getStringExtra("TYB"));
		}		
	};
	
	/**
	 * 关闭手势密码广播
	 */
	private BroadcastReceiver closeGesReceiver = new BroadcastReceiver(){
		public void onReceive(Context context, Intent intent) {
			user.setTradepwd("");			
		}		
	};
	
	/**
	 * 修改手势密码广播
	 */
	private BroadcastReceiver changeGesReceiver = new BroadcastReceiver(){
		public void onReceive(Context context, Intent intent) {
			user.setGstpwd(intent.getStringExtra("GES_PWD"));			
		}		
	};
	
	/**
	 * 版本更新广播
	 */
	private BroadcastReceiver updateReceiver = new BroadcastReceiver(){

		public void onReceive(Context context, Intent intent) {
			mHandler.sendEmptyMessage(12);
		}		
	};
	
	/**
	 * 开元通宝转到市场广播
	 */
	private BroadcastReceiver ybtmktReceiver = new BroadcastReceiver(){

		public void onReceive(Context context, Intent intent) {
			String num = intent.getStringExtra("NUM");
			if(num!=null){
				user.settYb(num);
			}
		}		
	};

	/**
	 * 下载服务启动器
	 */
	ServiceConnection conn = new ServiceConnection() {

		public void onServiceDisconnected(ComponentName name) {
			isBinded = false;
		}

		public void onServiceConnected(ComponentName name, IBinder service) {
			binder = (DownloadBinder) service;
			// 开始下载
			isBinded = true;
			binder.start();
		}
	};
	
	private Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
				case 0:
					Toast.makeText(MainActivity.this, "连接服务器失败，请检查网络", Toast.LENGTH_SHORT).show();
					break;
				case 1:
					//登陆成功
					new BagTask().execute();
					break;
				case 2:
					Toast.makeText(MainActivity.this, "信息同步失败", Toast.LENGTH_SHORT).show();
					break;
				case 3:
					//获取钱包数据成功
					Toast.makeText(MainActivity.this, "信息同步成功", Toast.LENGTH_SHORT).show();
					Util.saveObject(MainActivity.this, "USERS", user, "USERINFOS");
					break;				
				case 10:
					Toast.makeText(MainActivity.this, "连接服务器失败，请检查网络", Toast.LENGTH_SHORT).show();
					break;
				case 11:
					//获取版本信息成功
					if(serVersion!=null){
						if(!curVersion.equals(serVersion)){
							//发现新版本,提示下载
//							new UpDateDialog(MainActivity.this, R.style.dialog, serVersion).show();
						}
					}		
					break;
				case 12:
					//版本更新
					Intent intent= new Intent(MainActivity.this, DownloadService.class);
					intent.putExtra("URL", newVersionDownLoadUrl);
					startService(intent);
					bindService(intent, conn, Context.BIND_AUTO_CREATE);
					break;
			}
		};
	};
	protected void onCreate(Bundle savedInstanceState) {		
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		inflater = LayoutInflater.from(this);	
		initWebSocket();
		initHome();
		initView();
		initUser();
		initAssets();
		initMyself();
		initLoginReceiver();
		initExitReceiver();
		setContentView(homeView);
		initCurVersion();
		new VersionTask().execute();		
		initChgLgPwdReceiver();
		initTPwdOkReceiver();
		initChangeGesReceiver();
		initCloseGesReceiver();
		initUpdateReceiver();	
		initYbtmtkReceiver();
		initBuyReceiver();
		initSaleReceiver();
		init();
	}
	
	private void initUser(){
		user = (User) getIntent().getSerializableExtra("USER");
		if(user!=null){
			isLogin = true;
			hFragment.setUser(user);
		}
		initHomeTitle();
	}
	
	private void initView(){
		tvLgOrRt = (TextView) homeView.findViewById(R.id.tvLgOrRt);
	}
	
	private void init(){
		String type = getIntent().getStringExtra("CHANGE");
		if(type!=null){
			if(type.equals("change")){
				Toast.makeText(MainActivity.this, "设置成功，请重新登录", Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	/**
	 * 初始化webSocket
	 */
	private void initWebSocket(){
		GlobalApplication.client = new WebSocketClient(MainActivity.this);
	}
	private void initLoginReceiver(){
		IntentFilter filter = new IntentFilter();
		filter.addAction("com.zlwy.LOGIN");
		MainActivity.this.registerReceiver(loginReceiver, filter);
	}
	
	private void initBuyReceiver(){
		IntentFilter filter = new IntentFilter();
		filter.addAction("COM.ZLWY.BUYING");
		MainActivity.this.registerReceiver(buyReceiver, filter);
	}
	
	private void initSaleReceiver(){
		IntentFilter filter = new IntentFilter();
		filter.addAction("COM.ZLWY.SALING");
		MainActivity.this.registerReceiver(saleReceiver, filter);
	}
	
	private void initChgLgPwdReceiver(){
		IntentFilter filter = new IntentFilter();
		filter.addAction("com.zlwy.CHGLGPWD");
		MainActivity.this.registerReceiver(chgLgPwdReceiver, filter);
	}
	
	private void initYbtmtkReceiver(){
		IntentFilter filter = new IntentFilter();
		filter.addAction("COM.ZLWY.YBTMKT");
		MainActivity.this.registerReceiver(ybtmktReceiver, filter);
	}
	
	private void initTPwdOkReceiver(){
		IntentFilter filter = new IntentFilter();
		filter.addAction("com.zlwy.SETPAYPWDOK");
		MainActivity.this.registerReceiver(setTPwdOkReceiver, filter);
	}
	
	private void initExitReceiver(){
		IntentFilter filter = new IntentFilter();
		filter.addAction("COM.ZLWY.EXIT");
		MainActivity.this.registerReceiver(exitReceiver, filter);
	}
	
	private void initCloseGesReceiver(){
		IntentFilter filter = new IntentFilter();
		filter.addAction("com.zlwy.CLOSE_GES");
		MainActivity.this.registerReceiver(closeGesReceiver, filter);
	}
	
	private void initChangeGesReceiver(){
		IntentFilter filter = new IntentFilter();
		filter.addAction("com.zlwy.CHANGE_GES");
		MainActivity.this.registerReceiver(changeGesReceiver, filter);
	}
	
	private void initUpdateReceiver(){
		IntentFilter filter = new IntentFilter();
		filter.addAction("com.zlwy.UPDATE");
		MainActivity.this.registerReceiver(updateReceiver, filter);
	}
	
	private void initPager(){
		pager = (MyViewPager) homeView.findViewById(R.id.myPager);
		hFragment = new HomeFragment();
		fragments.add(hFragment);
		cFragment = new CandleFragment();
		fragments.add(cFragment);
		pagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(), fragments);
		pager.setAdapter(pagerAdapter);
	}
	
	@SuppressLint({ "InflateParams", "NewApi" })
	@SuppressWarnings("deprecation")
	private void initMyself(){
		selfView = inflater.inflate(R.layout.myself, null);
		TextView tvTitle = (TextView) selfView.findViewById(R.id.tvHomeTitle);
		tvTitle.setText(Util.getResourcesStr(R.string.myselfes));
		ImageView ivAssets = (ImageView) selfView.findViewById(R.id.ivMyself);
		ivAssets.setBackground(getResources().getDrawable(R.drawable.myself_selector));
		ImageView ivBack = (ImageView) selfView.findViewById(R.id.ivBackTitle);
		ivBack.setVisibility(View.GONE);
		ImageView ibtnBack = (ImageView) selfView.findViewById(R.id.iBtnBackTitle);
		ibtnBack.setVisibility(View.GONE);
		LinearLayout layoutLgOrRt = (LinearLayout) selfView.findViewById(R.id.layoutLgOrRg);
		layoutLgOrRt.setVisibility(View.GONE);
	}
	
	private void initMyselfLogin(){
		TextView tvIsLogin = (TextView) selfView.findViewById(R.id.tvIsLogin);
		if(isLogin){
			String phone = user.getPhone().substring(0, 3)+"****"+user.getPhone().substring(7);
			tvIsLogin.setText(phone);
		}else{
			tvIsLogin.setText(Util.getResourcesStr(R.string.unLogin));
		}
	}
	
	@SuppressLint({ "NewApi", "InflateParams" })
	@SuppressWarnings("deprecation")
	private void initAssets(){
		assetsView = inflater.inflate(R.layout.assets, null);
		TextView tvTitle = (TextView) assetsView.findViewById(R.id.tvHomeTitle);
		tvTitle.setText(Util.getResourcesStr(R.string.assetes));
		ImageView ivAssets = (ImageView) assetsView.findViewById(R.id.ivAssets);
		ivAssets.setBackground(getResources().getDrawable(R.drawable.assets_selector));
		ImageView ivBack = (ImageView) assetsView.findViewById(R.id.ivBackTitle);
		ivBack.setVisibility(View.GONE);
		ImageView ibtnBack = (ImageView) assetsView.findViewById(R.id.iBtnBackTitle);
		ibtnBack.setVisibility(View.GONE);
		LinearLayout layoutLgOrRt = (LinearLayout) assetsView.findViewById(R.id.layoutLgOrRg);
		layoutLgOrRt.setVisibility(View.GONE);
	}
	
	@SuppressLint({ "InflateParams", "NewApi" })
	@SuppressWarnings("deprecation")
	private void initHome(){
		homeView = inflater.inflate(R.layout.main, null);
		TextView tvTitle = (TextView) homeView.findViewById(R.id.tvHomeTitle);
		tvTitle.setText(Util.getResourcesStr(R.string.conjuncture));
		ImageView ivMyself = (ImageView) homeView.findViewById(R.id.ivConjuncture);
		ivMyself.setBackground(getResources().getDrawable(R.drawable.conjuncture_selector));
		ImageView ivBack = (ImageView) homeView.findViewById(R.id.ivBackTitle);
		ivBack.setVisibility(View.GONE);
		ImageView ibtnBack = (ImageView) homeView.findViewById(R.id.iBtnBackTitle);
		ibtnBack.setVisibility(View.GONE);
		initPager();
	}
	private void initHomeTitle(){	
		if(isLogin){
			tvLgOrRt.setText(Util.getResourcesStr(R.string.exit));
		}else{
			tvLgOrRt.setText(Util.getResourcesStr(R.string.loginOrRegister));
		}
	}
	
	/**
	 * 获取当前版本信息
	 */
	private void initCurVersion(){
		PackageManager manager;
		PackageInfo info = null;
		manager = this.getPackageManager();
		try {		
			info = manager.getPackageInfo(this.getPackageName(), 0);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		curVersion = info.versionName;
	}
	
	public void doClick(View v){
		
		Intent intent = null;
		Bundle b = null;
		switch (v.getId()) {
			case R.id.layoutMyself:
				setContentView(selfView);
				initMyselfLogin();
				break;
			case R.id.layoutAssets:
				setContentView(assetsView);
				break;
			case R.id.layoutConjuncture:
				setContentView(homeView);
				break;
			case R.id.layoutLgOrRg:
				//登陆注册
				if(isLogin){
					//退出
					new ExitDialog(MainActivity.this, R.style.dialog).show();
				}else{
					//登录
					intent = new Intent(MainActivity.this, LoginActivity.class);
					MainActivity.this.startActivity(intent);
				}
				
				break;
			case R.id.layoutRecommend:
				//推荐好友
				intent = new Intent(MainActivity.this, ShareActivity.class);
				myStart(intent);
				break;
			case R.id.layoutPrize:
				//领取奖励
				intent = new Intent(MainActivity.this, RewardActivity.class);
				myStart(intent);
				break;
			case R.id.layoutHatch:
				intent = new Intent(MainActivity.this, HatchActivity.class);
				myStart(intent);
				break;
			case R.id.layoutEbList:
				intent = new Intent(MainActivity.this, EbActivity.class);
				myStart(intent);
				break;
			case R.id.layoutYbList:
				intent = new Intent(MainActivity.this, YbActivity.class);
				myStart(intent);
				break;
			case R.id.layoutUsdList:
				intent = new Intent(MainActivity.this, UsdActivity.class);
				myStart(intent);
				break;
			case R.id.layoutBank:
				intent = new Intent(MainActivity.this, BankActivity.class);
				myStart(intent);
				break;
			case R.id.layoutYbToMarket:
				intent = new Intent(MainActivity.this, YbToMktActivity.class);
				myStart(intent);
				break;
			case R.id.layoutPwdManager:
				//密码管理
				intent = new Intent(MainActivity.this, PassMannagerActivity.class);
				myStart(intent);
				break;
			case R.id.layoutPersonal:
				intent = new Intent(MainActivity.this, PersonalInfoActivity.class);
				myStart(intent);
				break;
			case R.id.layoutNewVersion:
				//版本更新
				intent = new Intent(MainActivity.this, VersionActivity.class);
				intent.putExtra("VERSION", curVersion);
				startActivity(intent);
				break;
			case R.id.layoutRefrensh:
				//信息同步
				if(!isLogin){
					Toast.makeText(MainActivity.this, "请先登录", Toast.LENGTH_SHORT).show();
					return ;
				}
				new LoginTask().execute();
				break;
			case R.id.layoutExit:
				//退出 
				if(isLogin){
					new ExitDialog(MainActivity.this, R.style.dialog).show();
				}else{
					Toast.makeText(MainActivity.this, "请先登录", Toast.LENGTH_SHORT).show();
				}			
				break;
		}
	}
	
	private void myStart(Intent intent ){
		
		if(!isLogin){
			Toast.makeText(MainActivity.this, "请先登录", Toast.LENGTH_SHORT).show();
			return ;
		}
		Bundle b = new Bundle();
		b.putSerializable("USER", user);
		intent.putExtras(b);
		MainActivity.this.startActivity(intent);
	}

	private long mExitTime = 0;
	public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
                if ((System.currentTimeMillis() - mExitTime) > 2000) {
                        Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                        mExitTime = System.currentTimeMillis();

                } else {
                        finish();
                }
                return true;
        }
        return super.onKeyDown(keyCode, event);
	}

	/**
	 * 登录
	 */
	private void login(){
		if(!Util.isNetworkConnected()){
			mHandler.sendEmptyMessage(10);
			return;
		}
		LoginRequest request = new LoginRequest();
		C_Result result = request.login(user.getPhone(), user.getPs());	
		String str = (String) result.mData;
		if(str==null||str.equals("")){
			mHandler.sendEmptyMessage(10);
			return;
		}else{
			try {
				JSONObject obj = new JSONObject(str);
				if(obj!=null){
					
					if(!obj.isNull("uid")){
						String uid = obj.getString("uid");
						user.setUid(uid);
					}
					if(!obj.isNull("passwd")){
						String pwd = obj.getString("passwd");
						user.setPs(pwd);
					}
					if(!obj.isNull("mobile_type")){
						String mobileType = obj.getString("mobile_type");
						user.setMobileType(mobileType);
					}
					if(!obj.isNull("shareid")){
						String shareid = obj.getString("shareid");
						user.setShareid(shareid);
					}
					if(!obj.isNull("login_ip")){
						String login_ip = obj.getString("login_ip");
						user.setLogin_ip(login_ip);
					}
					if(!obj.isNull("gstpwd")){
						String gstpwd = obj.getString("gstpwd");
						user.setGstpwd(gstpwd);
					}
					if(!obj.isNull("cid")){
						String cid = obj.getString("cid");
						user.setCid(cid);
					}
					if(!obj.isNull("regist_time")){
						String regist_time = obj.getString("regist_time");
						user.setRegist_time(regist_time);
					}
					if(!obj.isNull("bankcard")){
						String bankcard = obj.getString("bankcard");
						user.setBankcard(bankcard);
					}
					if(!obj.isNull("hatch_level")){
						String hatch_level = obj.getString("hatch_level");
						user.setHatch_level(hatch_level);
					}
					if(!obj.isNull("login_time")){
						String login_time = obj.getString("login_time");
						user.setLogin_time(login_time);
					}
					
					if(!obj.isNull("rid")){
						String rid = obj.getString("rid");
						user.setRid(rid);
					}
					
					if(!obj.isNull("tradepwd")){
						String tradepwd = obj.getString("tradepwd");
						user.setTradepwd(tradepwd);
					}
					
					if(!obj.isNull("account")){
						String account = obj.getString("account");
						user.setAccount(account);
						user.setPhone(account);
					}
					
					if(!obj.isNull("hatch_acount")){
						String hatch_acount = obj.getString("hatch_acount");
						user.setAccount(hatch_acount);
					}
					if(!obj.isNull("headid")){
						String headid = obj.getString("headid");
						user.setHeadid(headid);
					}
					if(!obj.isNull("rslt")){
						String rslt = obj.getString("rslt");
						int message = Integer.parseInt(rslt);
						mHandler.sendEmptyMessage(2);
					}else{
						mHandler.sendEmptyMessage(1);
					}
					
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	private class LoginTask extends AsyncTask<Void, Void, Void>{

		protected Void doInBackground(Void... param) {
			login();
			return null;
		}
		
	}
	
	/**
	 *获取钱包数据
	 */
	private void setBag() {
		if(!Util.isNetworkConnected()){
			mHandler.sendEmptyMessage(10);
			return;
		}
		BagRequest request = new BagRequest();
		C_Result result = request.bag(user.getUid());
		String str = (String) result.mData;
		JSONObject jMsg = null;
		int message = result.getmResult();
		try {
			if(str==null||str.equals("")){
				mHandler.sendEmptyMessage(10);
				return;
			}
			jMsg = new JSONObject(str);
			if (jMsg != null) {
				if (!jMsg.isNull("uid")) {
					String uid = jMsg.getString("uid");
					user.setUid(uid);
				}
				if (!jMsg.isNull("k_coin_lock")) {
					String lock = jMsg.getString("k_coin_lock");
					user.setLock(lock);
				}
				if (!jMsg.isNull("e_coin")) {
					String ebNum = jMsg.getString("e_coin");
					BigDecimal db = new BigDecimal(ebNum);
					String ebNums = db.toPlainString();
					user.setEbNum(Util.dealStrs(ebNums, 1));
				}
				if (!jMsg.isNull("v_coin")) {
					String mjNum = jMsg.getString("v_coin");
					BigDecimal db = new BigDecimal(mjNum);
					String mjNums = db.toPlainString();
					user.setMjNum(Util.dealStrs(mjNums, 3));
				}
				if (!jMsg.isNull("k_coin")) {
					String ybNum = jMsg.getString("k_coin");
					BigDecimal db = new BigDecimal(ybNum);
					String ybNums = db.toPlainString();
					user.setYbNum(Util.dealStrs(ybNums, 2));
				}
				if(!jMsg.isNull("wid")){
					String wid = jMsg.getString("wid");
					user.setWid(wid);
				}
				message = 3;
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mHandler.sendEmptyMessage(message);
	}
	
	private class BagTask extends AsyncTask<Void, Void, Void> {
		protected Void doInBackground(Void... arg0) {
			setBag();
			return null;
		}
	}
	
	/**
	 * 获取版本信息
	 */
	private void getVersion(){
		VersionRequest request = new VersionRequest();
		C_Result result = request.versionRequest();
		String str = (String) result.mData;
		JSONObject jMsg = null;
		int message = 0;
		if(str!=null)
		try {
			jMsg = new JSONObject(str);
			if (jMsg != null) {
				if (!jMsg.isNull("var")) {
					 serVersion = jMsg.getString("var");
				}
				if (!jMsg.isNull("url")) {
					 newVersionDownLoadUrl = jMsg.getString("url");
				}
				message =11;
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mHandler.sendEmptyMessage(message);
	}
	
	private class VersionTask extends AsyncTask<Void, Void, Void>{

		protected Void doInBackground(Void... arg0) {
			getVersion();
			return null;
		}		
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(loginReceiver!=null){
			MainActivity.this.unregisterReceiver(loginReceiver);
			loginReceiver = null;
		}
		if(chgLgPwdReceiver!=null){
			MainActivity.this.unregisterReceiver(chgLgPwdReceiver);
			chgLgPwdReceiver = null;
		}
		if(setTPwdOkReceiver!=null){
			MainActivity.this.unregisterReceiver(setTPwdOkReceiver);
			setTPwdOkReceiver = null;
		}
		if(updateReceiver!=null){
			MainActivity.this.unregisterReceiver(updateReceiver);
			updateReceiver = null;
		}
		if(closeGesReceiver!=null){
			MainActivity.this.unregisterReceiver(closeGesReceiver);
			closeGesReceiver = null;
		}	
		if(changeGesReceiver!=null){
			MainActivity.this.unregisterReceiver(changeGesReceiver);
			changeGesReceiver = null;
		}
		
		if(exitReceiver!=null){
			MainActivity.this.unregisterReceiver(exitReceiver);
			exitReceiver = null;
		}
		
		if(buyReceiver!=null){
			MainActivity.this.unregisterReceiver(buyReceiver);
			buyReceiver = null;
		}
		
		if(saleReceiver!=null){
			MainActivity.this.unregisterReceiver(saleReceiver);
			saleReceiver = null;
		}
		
		if(ybtmktReceiver!=null){
			MainActivity.this.unregisterReceiver(ybtmktReceiver);
			ybtmktReceiver = null;
		}
		
		if(isBinded){
			MainActivity.this.unbindService(conn);
		}
		
		if (binder != null && binder.isCanceled()) {
			Intent it = new Intent(this, DownloadService.class);
			stopService(it);
		}

	}
}
